package com.powernode.config;

import com.powernode.constant.AuthConstants;
import com.powernode.handle.AuthenticationFailureHandlerImpl;
import com.powernode.handle.AuthenticationSuccessHandlerImpl;
import com.powernode.handle.LogoutSuccessHandlerImpl;
import com.powernode.impl.UserDetailServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName AuthSecurityConfig
 * @Description Security安全框架配置类
 * @Date 2024/07/20 19:54
 */
@Component
public class AuthSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailServiceImpl userDetailService;
    @Resource
    private AuthenticationSuccessHandlerImpl authenticationSuccessHandler;
    @Resource
    private AuthenticationFailureHandlerImpl authenticationFailureHandler;
    @Resource
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    /**
     * 设置Security安全框架内走自己的认证流程
     * @param auth AuthenticationManagerBuilder
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                // 关闭跨站请求伪造/跨域请求/session使用策略
                .cors().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
                // 登录相关配置
                .formLogin()
                .loginProcessingUrl(AuthConstants.LOGIN_URL)
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
            .and()
                // 登出相关配置
                .logout()
                .logoutUrl(AuthConstants.LOGOUT_URL)
                .logoutSuccessHandler(logoutSuccessHandler)
            .and()
                // 其它任何请求都必须认证
                .authorizeHttpRequests().anyRequest().authenticated();

    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
